'''
Author: Finlay
Date: 2022-03-13 12:08:33
LastEditTime: 2022-03-13 15:08:53
LastEditors: Please set LastEditors
Description: 利用Python脚本获取域名物理IP，进行周期测试判断该域名是否为负载均衡。
FilePath: /python/domain/domain.py
'''

import time
import threading
import socket

# 日志记录
def logs(error="warning",message="request"):
    ite = open("domain.log","a");
    str = "[%s] %s %s \n" % (error,time.asctime( time.localtime(time.time()) ),message)
    ite.write(str)
    return True

# 写入数据
def adddata(name,ip):
    ite = open("data/"+name+".txt","r")
    if ip in ite.read() == False:
        writ = open("data/"+name+".txt","a")
        writ.write(ip+"\n")
    return True

# 定时器
def doing():
    global timer
    readtxt("domain.txt")
    timer = threading.Timer(3600,doing) # 每小时执行一次
    timer.start()

# 读取文件并解析
def readtxt(path):
    with open(path,"r") as i:
        for domain in i.readlines():
            domain = domain.strip('\n')
            try:
                ip = socket.getaddrinfo(host=domain,port=None)
                adddata(domain,ip[0][4][0])
            except Exception as err:
                logs("error",err)
        

if __name__ == '__main__':

    setTime = True # True or Flase ,定时器开关
    if setTime:
        doing() # 执行定时器
        time.sleep(3600*24*7) # 等待一周后执行
        timer.cancel()  # 关闭定时器
    else:
        readtxt("domain.txt")